#include "Logger.h"
#include <iostream>
#include <stdio.h>
#include <time.h>

#define OPENING_TEXT "Log started"
#define CLOSING_TEXT "Log closed"

using std::clog;

Logger mainLog("",true,true);
Logger errLog("err.log",true,false);


Logger::Logger(Str &filename,bool echo,bool startClose){
    load(!filename,echo,startClose);
}
Logger::Logger(const char *filename, bool echo,bool startClose){
    load(filename,echo,startClose);
}
Logger::~Logger(){
    if (_sc)
    {print(CLOSING_TEXT);}
}
void	Logger::load(const char *filename, bool echo,bool startClose){
    _echo=echo;
    _sc=startClose;
    fn=filename;
    if (_sc)
    {print(OPENING_TEXT);}
}
bool	Logger::timestamp(){
    Str t;
    time_t ltime;
    ltime=time(0);
    t << asctime(localtime(&ltime));
    t.deleteRight(1);//to get rid of the \n at the end
    t << ": ";
    
    if (fn.size()!=0)
    {
        FILE *f;
        f=fopen(!fn,"a");
        if (f==0){fn.clear();return false;}
        else
        {
            fputs(!t,f);
            fclose(f);
        }
    }
    if (_echo){clog<<!t;}
    return true;
}
Logger&	Logger::print(Str &text){
    return print(!text);
}
Logger&	Logger::print(const char *text){
    if (!timestamp()){return *this;}//failed
    if (fn.size()!=0)
    {
        FILE *f;
        f = fopen(!fn,"a");
        if (f==0){fn.clear();}
        else
        {
            fputs(text,f);
            fputs("\n",f);
            fclose(f);
        }
    }
    if (_echo){clog<<text<<"\n";}
    return *this;
}
Logger& Logger::buffer(Str &text){
	return buffer(!text);
}
Logger& Logger::buffer(const char *text){
	Str t,tt;
	t=text;
	while (t.size()>0)
	{
		bool sendit=false;
		if (t.findChar('\n')>0){sendit=true;}
		tt.getFromMark("\n", t);
		buff<<tt;
		if (sendit){print(buff);}
	}
	return *this;
}
Logger& Logger::operator<<(const char *text){
	return buffer(text);
}
Logger& Logger::operator<<(Str &text){
	return buffer(text);
}
Logger&	Logger::operator()(Str &text){return print(!text);}
Logger&	Logger::operator()(const char *text){return print(text);}
